<template>
	<view style="width: 100%;background: #f3f3f3;">
		<bgyx-nav-bar>
			<view slot="left">
				<u-icon @click="goback" name="arrow-left" size="36"></u-icon>
			</view>
			<view slot="default">
				<b style="font-size: 32rpx;">{{$store.state.gchat.group[id].name}}</b>
			</view>
			<view slot="right" style="display: flex;justify-content: flex-end;align-items: center;">
				<u-icon @click="goGroupInfo" name="more-circle" size="42"></u-icon>
			</view>
		</bgyx-nav-bar>

		<view
			style="width: 100%;display: flex; padding-bottom: 120rpx;height: calc(100vh - 120rpx);flex-direction: column;">
			<scroll-view :upper-threshold="50" :scroll-with-animation="true" :scroll-top="scrollTop"
				:scroll-into-view="anc" :scroll-y="true" style="height: 100%;" @scrolltolower="lower" @scroll="scroll">

				<view style="display: flex;flex-direction: column-reverse;" @catchtouchmove="catchTouchMove">
					<view style="width: 100%;height: 50px;display: flex;">
						<view id="bottomHref"></view>
						<view id="bottomHrefx"></view>
					</view>
					<view v-for="(item,k) in messages">
						<gmsgTextItem :user_id="item.user_id" :group_id="item.group_id" v-if="item.type == 'text'"
							:myMsg="$store.state.user.user.id == item.user_id" :content="item.content" />
						<gmsgEmojiItem :user_id="item.user_id" :group_id="item.group_id" v-if="item.type == 'emoji'"
							:myMsg="$store.state.user.user.id == item.user_id" :content="item.content" />
						<gmsgSystemItem :content="item.content" v-if="item.type == 'system'" />
						<gmsgImageItem :user_id="item.user_id" :group_id="item.group_id" v-if="item.type == 'image'"
							:myMsg="$store.state.user.user.id == item.user_id" :src="item.src" />
						<gmsgVoiceItem :user_id="item.user_id" :group_id="item.group_id" v-if="item.type == 'voice'"
							:myMsg="$store.state.user.user.id == item.user_id" :src="item.src"
							:timelong="item.timelong" />
						<gmsgVideoItem :user_id="item.user_id" :group_id="item.group_id" v-if="item.type == 'video'"
							:myMsg="$store.state.user.user.id == item.user_id" :width="item.video_width"
							:height="item.video_height" :src="item.src" />
					</view>
					<view v-if="loading"
						style="width: 100%;height: 120px;display: flex;align-items: flex-end;justify-content: center;">
						<view style="height: 20px;">
							<u-loading mode="circle"></u-loading>
						</view>
					</view>
				</view>
			</scroll-view>

		</view>

		<view
			style="width: 100%;height: 110rpx;display: flex;background: white;position: fixed;bottom: 0rpx;background: #f8f8f8;align-items: center;">
			<view style="margin-left: 20rpx;margin-top: 5rpx;">
				<image v-if="inputModel == 'keybord'" @click="inputModel = 'voice'" src="/static/images/icon_speak.png"
					style="width: 60rpx;height: 60rpx;" mode=""></image>
				<image v-if="inputModel == 'voice'" @click="inputModel = 'keybord'"
					src="/static/images/icon_keybord.png" style="width: 60rpx;height: 60rpx;" mode=""></image>
			</view>
			<view style="margin-left: 20rpx;margin-top: 5rpx;flex:1;">
				<u-input v-if="inputModel == 'keybord'" :adjust-position="false" :confirm-hold="true"
					confirm-type="send" v-model="sendMessage" @confirm="sendStr" :auto-height="true" :border="true" />
				<view @touchstart="startRecord" @touchend="endRecord" @touchcancel="cancelRecord" @touchmove="moveTch"
					v-if="inputModel == 'voice'"
					style="display: flex;align-items: center;justify-content: center;border-radius: 10rpx;background: #ebebeb;width: 100%;height: 70rpx;">
					<text class="">
						按住
					</text>
					<view class="">
						<image src="/static/images/icon_mic.png" style="width: 40rpx;height: 40rpx;" mode=""></image>
					</view>
					<text class="">
						说话
					</text>
				</view>
			</view>
			<view style="margin-left: 20rpx;margin-top: 5rpx;">
				<bgyx-emoji :onSelect="onSelect" />
			</view>
			<view style="margin-left: 20rpx;margin-top: 5rpx;margin-right: 20rpx;">
				<image @click="showUpTool = true" src="/static/images/icon_addmenu.png"
					style="width: 60rpx;height: 60rpx;" mode=""></image>
			</view>
		</view>

		<u-action-sheet @click="clickToolItem" :list="toollist" v-model="showUpTool"></u-action-sheet>


		<view v-if="loading"
			style="position: fixed;top: 0rpx;left: 0rpx;width: 100%;height: calc(100vh - 110rpx);z-index: 9999;">

		</view>

		<view v-if="recording" class="recordbg">
			<image src="/static/images/icon_recording.png" style="width: 160rpx;height: 160rpx;" mode=""></image>
			<text style="margin: 20rpx auto;color:#2fc274;">录音中</text>
		</view>

	</view>
</template>

<script>
	// #ifdef APP-PLUS
	var Color = plus.android.importClass("android.graphics.Color");
	plus.android.importClass("android.view.Window");
	var mainActivity = plus.android.runtimeMainActivity();
	var window_android = mainActivity.getWindow();
	window_android.setNavigationBarColor(Color.parseColor("#f8f8f8"));
	// #endif
	import gmsgTextItem from '../components/gmsgTextItem.vue'
	import gmsgSystemItem from '../components/gmsgSystemItem.vue'
	import gmsgEmojiItem from '../components/gmsgEmojiItem.vue'
	import gmsgImageItem from '../components/gmsgImageItem.vue'
	import gmsgVoiceItem from '../components/gmsgVoiceItem.vue'
	import gmsgVideoItem from '../components/gmsgVideoItem.vue'
	import utils from '../../../utils';
	import {
		mapState
	} from 'vuex';
	import {
		sub,
		unsub
	} from '../../../common/event';
	import moment from 'moment';
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	export default {
		data() {
			return {
				id: '',
				anc: '',
				inputModel: 'keybord',
				sendMessage: '',
				scrollTop: 0,
				showUpTool: false,
				loading: false,
				toollist: [{
					text: "上传图片",
					value: "image"
				}, {
					text: "上传视频",
					value: "video"
				}],
				touchY: '',
				touchEndY: '',
				voices: 0,
				voicee: 0,
				voiceStatus: 0,
				recording: false
			}
		},
		components: {
			gmsgTextItem,
			gmsgImageItem,
			gmsgVoiceItem,
			gmsgVideoItem,
			gmsgEmojiItem,
			gmsgSystemItem
		},
		computed: {
			...mapState({
				messages: state => {
					return state.gchat.messages.filter((item) => {
						return item.group_id == state.gchat.currentId
					})
				},
				status: state => {
					const _this = this
					return state.gchat.status[state.gchat.currentId]
				}
			})
		},
		watch: {
			messages: function(a, b) {
				const _this = this
				// this.$nextTick(() => {
				// 	_this.anc = _this.anc == "bottomHref" ? "bottomHrefx" : "bottomHref"
				// })
			}
		},
		onLoad({
			id
		}) {
			const _this = this
			this.id = id
			this.$store.commit(`gchat/setCurrentState`, id)
			this.$nextTick(() => {
				_this.anc = _this.anc == "bottomHref" ? "bottomHrefx" : "bottomHref"
			})
			sub('vuex_gchat_addMessage', this.onGetMessage)
			this.$store.dispatch({
				type: "chats/updateGReTime",
				payload: this.id
			})
			this.$store.commit(
				"chats/onGRead",
				this.id
			)
		},
		onUnload() {
			unsub('vuex_gchat_addMessage', this.onGetMessage)
			this.$store.dispatch({
				type: "chats/updateGReTime",
				payload: this.id
			})
			this.$store.commit(
				"chats/onGRead",
				''
			)
		},
		onReady() {
			const _this = this
			recorderManager.onStop(async function(res) {
				console.log('recorder stop' + JSON.stringify(res));
				const timelong = Math.floor((_this.voicee - _this.voices) / 1000)
				if (_this.voiceStatus == 1) {
					const voicePath = res.tempFilePath;
					const ret = await utils.uploadAudio(voicePath)
					const message = {
						type: "voice",
						user_id: _this.$store.state.user.user.id,
						group_id: _this.id,
						src: ret.data.pathname,
						timelong
					}
					_this.$socket.send({
						type: "gmessage",
						data: message
					})
				}

			});
		},
		methods: {
			goGroupInfo: function() {
				uni.navigateTo({
					url: "/pages/address/userinfo/group?id=" + this.id
				})
			},
			onGetMessage: function() {
				const _this = this
				_this.$nextTick(() => {
					_this.anc = _this.anc == "bottomHref" ? "bottomHrefx" : "bottomHref"
				})
			},
			getSettings: async function() {
				return new Promise((r) => {
					uni.getSetting({
						success: (res) => {
							console.log('res.authSetting', res.authSetting['scope.record']);
							if (res.authSetting['scope.record'] == false) {
								uni.showToast({
									title: '请先开启授权',
									icon: 'none'
								})
								uni.authorize({
									scope: 'scope.record',
									success: (res) => {
										r(true)
									},
									fail: (res) => {
										r(false)
									}
								})
							} else {
								r(true)
							}

						}
					})
				})
			},
			startRecord: async function(e) {
				// const authorize = await this.getSettings()
				// if(!authorize) return
				this.voiceStatus = 0
				this.touchY = e.changedTouches[0].clientY
				this.voices = moment().valueOf()
				this.recording = true
				recorderManager.start()
			},
			endRecord: function(e) {
				if (this.touchEndY && this.touchY - this.touchEndY > 30) {
					this.recording = false
					this.voiceStatus = 2
					uni.showToast({
						title: "已取消",
						icon: "none"
					})

					this.touchY = ''
					this.touchEndY = ''
					recorderManager.stop()
					return
				}
				this.voicee = moment().valueOf()
				console.log(`ssttop`, this.voicee)
				this.voiceStatus = 1
				this.touchY = ''
				this.touchEndY = ''
				this.recording = false
				recorderManager.stop()
			},
			cancelRecord: function(e) {
				this.voiceStatus = 2
				this.touchY = ''
				this.touchEndY = ''
				this.recording = false
				recorderManager.stop()
			},
			moveTch: function(e) {
				const touchY = e.changedTouches[0].clientY
				this.touchEndY = touchY
			},
			goback: function() {
				uni.switchTab({
					url:"/pages/index/index"
				})
			},
			clickToolItem: function(index) {
				console.log(index)
				switch (index) {
					case 0:
						this.upLoadImage()
						break;
					case 1:
						this.upLoadVideo()
						break;
					case 2:

						break;
					default:
						break;
				}
			},
			upLoadImage: async function() {
				const _this = this
				uni.chooseImage({
					count: 1,
					async success(e) {
						const file = e.tempFilePaths[0]
						const ret = await utils.uploadImage(file)
						const message = {
							type: "image",
							user_id: _this.$store.state.user.user.id,
							group_id: _this.id,
							src: ret.data.pathname,
						}
						_this.$socket.send({
							type: "gmessage",
							data: message
						})
					}
				})
			},
			upLoadVideo: async function() {
				const _this = this
				uni.chooseVideo({
					async success(e) {
						uni.showLoading({
							title:"视频上传中.."
						})
						uni.getVideoInfo({
							src: e.tempFilePath,
							async success(ee) {
								const file = e.tempFilePath
								const ret = await utils.uploadVideo(file)
								uni.hideLoading()
								const message = {
									type: "video",
									user_id: _this.$store.state.user.user.id,
									group_id: _this.id,
									src: ret.data.pathname,
									video_width: ee.width > 0 ? ee.width : ret.data.width,
									video_height: ee.height > 0 ? ee.height : ret.data.height,
								}
								_this.$socket.send({
									type: "gmessage",
									data: message
								})
							}
						})
					}
				})
			},
			sendStr: function() {
				const _this = this
				this.$socket.send({
					type: "gmessage",
					data: {
						user_id: this.$store.state.user.user.id,
						group_id: this.id,
						type: "text",
						content: this.sendMessage
					}
				})
				_this.sendMessage = ''
				// this.$nextTick(() => {
				// 	_this.anc = _this.anc == "bottomHref" ? "bottomHrefx" : "bottomHref"
				// 	_this.sendMessage = ''
				// })
			},
			onSelect: function(k) {
				const _this = this
				this.$socket.send({
					type: "gmessage",
					data: {
						user_id: this.$store.state.user.user.id,
						group_id: this.id,
						type: "emoji",
						content: "__emoji__" + k
					}
				})
			},
			getMore: function() {
				const _this = this
				this.$store.dispatch({
					type: "gchat/getMoreMessage",
					payload: {
						id: this.id,
						time: this.messages[this.messages.length - 1].create_time,
						currentId: this.messages[this.messages.length - 1].id,
						callback: function() {
							_this.loading = false
						}
					}
				})
			},
			moveHandle: function() {
				return true;
			},
			catchTouchMove: function(e) {
				return false;

			},
			lower: function(e) {
				// console.log(123112333, e)
			},
			scroll: function(e) {
				const status = this.status
				if (status.finish || this.loading) {
					return
				}
				if (this.loading && e.detail.scrollTop < 100) {
					this.scrollTop = 100 + Math.random()
				}
				if (e.detail.scrollTop < 100 && !this.loading) {
					this.loading = true
					this.scrollTop = 100 + Math.random()
					this.getMore()
				}
			},
		}
	}
</script>

<style scoped>
	.recordbg {
		width: 100%;
		height: 100vh;
		background: linear-gradient(to bottom, #fff, #222222aa, #111111dd);
		position: fixed;
		top: 0;
		left: 0;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
</style>